package com.supreme.nettyapp.generalserver.chatserver.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.net.InetAddress;
import java.util.Objects;

public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetAddress localHost = InetAddress.getLocalHost();
        String hostName = localHost.getHostName();
        String hostAddress = localHost.getHostAddress();
        ctx.writeAndFlush(String.format("[SERVER] Welcome Name = %s address = %s\n", hostName, hostAddress));
        channelGroup.add(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        for (Channel channel : channelGroup) {
            if (Objects.equals(channel, ctx.channel())) {
                channel.writeAndFlush("[you] " + msg + '\n');
            } else {
                channel.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
            }
        }
    }
}
